from django.shortcuts import render, HttpResponse, redirect
from django.urls import reverse
from django.views import View
from django.contrib import auth
from web import models
from web.form import BookForm

# Create your views here.

class Login(View):
    def get(self, request):
        return render(request, "web/login.html")
    
    def post(self, request):

        username = request.POST.get("username")
        password = request.POST.get("password")
        print(username, password)

        user_obj = auth.authenticate(username=username, password=password)
        if user_obj:
            request.session["is_login"] = True
            return redirect(reverse("web:bookList"))
        else:
            error = "用户名或密码错误"
            return render(request, "web/login.html", {"error": error})

class Register(View):
    def get(self, request):
        return render(request, "web/register.html")

    def post(self, request):
        print(request.POST)

        return HttpResponse("222")

class BookList(View):
    def get(self, request):
        book_obj_list = models.Book.objects.all()
        
        return render(request, "web/bookList.html", {"book_obj_list": book_obj_list})
    
class BookChange(View):
    def get(self, request, id=None):
        print(id)
        obj = models.Book.objects.filter(pk=id).first()
        form_obj = BookForm(instance=obj)
        content = "添加书籍"
        if id:
            content = "编辑书籍"
        return render(request, "web/bookChange.html", {"form_obj": form_obj, "content": content})
            
    def post(self, request, id=None):
        obj = models.Book.objects.filter(pk=id).first()
        print(request.POST)
        # <QueryDict: {
        # 'csrfmiddlewaretoken': ['MsyHkK8UeA9GCWqf5T8TVxz8wknVYL2hImzx0R0B1g0cuiMyAArlASbNzJ6Vhij2'],
        # 'title': ['平凡的世界'], 'price': ['100'], 'publish_date': ['2019-04-20'], 'publish': ['1'],
        # 'authors': ['1']}>
        form_obj = BookForm(request.POST, instance=obj)
        if form_obj.is_valid():
            form_obj.save()
            return redirect(reverse("web:bookList"))
        else:
            return render(request, "web/bookChange.html", {"form_obj": form_obj,})

class BookDelete(View):
    def get(self, request, id=None):
        models.Book.objects.filter(pk=id).delete()

        return redirect(reverse("web:bookList"))






    
    
    

